package com.vsen.lpr.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisUtils {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    /**
     * 指定缓存失效时间
     * @param key
     * @param time
     * @return
     */
    public boolean setExpire(String key,long time){
        try {
           if(time>0){
               redisTemplate.expire(key, time, TimeUnit.SECONDS);
           }
           return true;
        }catch (Exception e){
            log.error("设置key={}过期失败",key);
            return false;
        }


    }

    /**
     * 获取key的过期时间
     * @param key
     * @return
     */
    public Long getExpire(String key){
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    }


    /**
     * zset中插入输入
     * @param key 键
     * @param value 值
     * @param score 排序的键
     * @return 是否插入成功
     */
    public Boolean addZset(String key,Object value,Long score){
        try{
            return redisTemplate.opsForZSet().add(key, value, score);
        }catch (Exception e){
            log.error("向zSet中设置key={}失败",key);
            return false;
        }
    }

    /**
     * 获取指定key zset的大小
     * @param key
     * @return
     */
    public Long getZsetSizeByKey(String key){
        try {
            return redisTemplate.opsForZSet().size(key);

        }catch (Exception e){
            log.error("获取key={}zset的size失败",key);
            return -1L;
        }
    }

    /**
     * 获取指定范围的集合
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<Object> rengeZset(String key,Long start,Long end){
        if(Objects.isNull(start)||Objects.isNull(end)){
            return null;
        }
        if(start > end){
            return null;
        }

        try {
            return redisTemplate.opsForZSet().range(key, start, end);
        }catch (Exception e){
            return null;
        }
    }

    public Long deleteZset(String key,Object value){
        try{
            return redisTemplate.opsForZSet().remove(key, value);
        }catch (Exception e){
            log.error("zSet中删除数据key={}&&value={}失败",key,value);
            return -1L;
        }
    }

    public Double score(String key,Object value){
        try{
            return redisTemplate.opsForZSet().score(key, value);
        }catch (Exception e){
            log.error("zSet中删除数据key={}&&value={}失败",key,value);
            return -1D;
        }
    }







}
